/*
 * @Date: 2023-03-27 14:29:00
 * @LastEditors: Chuying
 * @LastEditTime: 2023-03-28 10:24:34
 * @Description:
 */
import { Injectable, BadRequestException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { CreateAuthDto } from './dto/create-auth.dto';
import { UpdateAuthDto } from './dto/update-auth.dto';
import { UserStatusDTO } from '../user/dto/user-status.dto';
import { LoginUserDto } from '../user/dto/login-user.dto';

import { UserService } from '../user/user.service';
// import { User } from '../user/entities/user.entity';

import * as _ from 'lodash';
import * as bcrypt from 'bcryptjs';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  // 登录接口服务层
  async login(userInfo: UserStatusDTO) {
    console.log('userInfo', userInfo);

    const token = this.createToken(userInfo);
    return {
      userInfo,
      ...token,
    };
  }

  createToken({ username, id: userId }: UserStatusDTO) {
    const token = this.jwtService.sign({ username, userId });
    const expires = process.env.expiresTime;
    return {
      token,
      expires,
    };
  }

  // 验证用户有效性，这个在local策略里用到
  async validateUser(loginUserDto: LoginUserDto): Promise<UserStatusDTO> {
    const username = loginUserDto?.username;
    const password = loginUserDto?.password;
    if (_.isEmpty(username) || _.isEmpty(password)) {
      throw new BadRequestException('请输入合法用户名!');
    }
    // 去数据库查找该user
    const user = await this.userService.findLoginUser(username);
    console.log(user);

    if (_.isEmpty(user)) {
      throw new BadRequestException('该账号不存在!');
    }
    const isValidPwd = await bcrypt.compare(password, user.password);
    if (!isValidPwd) {
      throw new BadRequestException('用户名密码不匹配!');
    }
    const sanitizedUser = {
      id: user.id,
      username: user.username,
      //   memo_count: user.memo_count,
      //   day_count: user.day_count,
      //   tag_count: user.tag_count,
      //   month_sign_id: user.month_sign_id,
      //   last_login: user.last_login,
    };
    return sanitizedUser;
  }

  create(createAuthDto: CreateAuthDto) {
    return 'This action adds a new auth';
  }

  findAll() {
    return `This action returns all auth`;
  }

  findOne(id: number) {
    return `This action returns a #${id} auth`;
  }

  update(id: number, updateAuthDto: UpdateAuthDto) {
    return `This action updates a #${id} auth`;
  }

  remove(id: number) {
    return `This action removes a #${id} auth`;
  }
}
